import 'package:flutter_share/constants/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TokenManager {
  // 定一个token变量
  // 因为获取token需要是一个同步方法，在拦截路由的时候不能写异步代码
  String? _token;
  String? _refreshToken;

  // "_"表示私有方法,获取存储实例
  Future<SharedPreferences> _getInstance() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs;
  }

  // 项目启动时进行初始化
  init() async {
    final prefs = await _getInstance();
    _token = prefs.getString(GlobalVariable.TOKEN) ?? "";
    _refreshToken = prefs.getString(GlobalVariable.REFRESH_TOEKN);
  }

  /// 存token
  Future<void> setToken(String token, String refreshToken) async {
    final prefs = await _getInstance();
    _token = token; // 设置token
    await prefs.setString(GlobalVariable.TOKEN, token); // token
    if (refreshToken.isNotEmpty) {
      prefs.setString(GlobalVariable.REFRESH_TOEKN, refreshToken);
      _refreshToken = refreshToken;
    }
  }

  /// 取token 必须是同步方法
  String getToken() {
    return _token ?? "";
  }

  /// 取refreshToken
  String getRefreshToken() {
    return _refreshToken ?? "";
  }

  /// 删token
  Future<void> deleteToken() async {
    final prefs = await _getInstance();
    _token = "";
    await prefs.remove(GlobalVariable.TOKEN);

    // 删除刷新token
    await prefs.remove(GlobalVariable.REFRESH_TOEKN);
    _refreshToken = null;
  }
}

// 单例模式
final tokenManager = TokenManager();
